package com.zhentao.controller;

import com.zhentao.pojo.Student;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileWriter;
import java.io.IOException;
import java.util.*;


@Controller
public class FreemarkerTestController {
    @Autowired
    private Configuration configuration;

    @RequestMapping("/t1")
    public String t1(Model model){
        //1，传递一个文本数据
        model.addAttribute("name","测试使用-小明");

        Student student=new Student();
        student.setAge(11);
        student.setName("张三");
        student.setBirthday(new Date());
        model.addAttribute("stu",student);

        Student student2=new Student();
        student2.setAge(22);
        student2.setName("李四");
        student2.setBirthday(new Date());
        List list=new ArrayList();
        list.add(student);
        list.add(student2);
        model.addAttribute("list",list);

        Map<String,Object> map=new HashMap<>();
        map.put("stu1", student);
        map.put("stu2", student2);
//        map.put("list", list);
        model.addAttribute("map",map);
        //跳转到一个页面   ---拼接成01-test.ftl
        return "01-test";
    }

    @ResponseBody
    @RequestMapping("/createHtml")
    public String createHtml() throws IOException, TemplateException {
        Template template=configuration.getTemplate("02.ftl");
        Student student=new Student();
        student.setName("小明");
        student.setAge(1111);

        Student student1=new Student();
        student1.setName("小红");
        student1.setAge(2222);

        List list=new ArrayList();
        list.add(student);
        list.add(student1);

        Map<String,Object> map=new HashMap<>();
        map.put("list", list);
        map.put("stu", student);
        template.process(map,new FileWriter("E:\\freemarker\\test\\03.html"));

        return "成功";
    }
}